import axios from 'axios'
import { getToken } from '@/utils/storage'
import { ElMessage } from 'element-plus'
import router from '@/router/index'
//import errorCode from '@/utils/error-code'
import gconfig from '@/config/global_config'
//ElMessageBox,

//axios.defaults.headers['Content-Type'] = "application/json;charset=utf-8"

const service = axios.create({
    //baseURL: "http://101.34.207.228:8081/"
    baseURL: gconfig.constants.API_ORIGIN
})


// 请求拦截
service.interceptors.request.use(config => {
    let needAuthentication = config.needAuthentication
    config.headers['Content-Type'] = 'application/json';
    // 设置令牌
    if (needAuthentication && getToken()) {
        config.headers['token'] = getToken()
    }
    let contentType = config.contentType;
    if (contentType == 'form') {
        config.headers['Content-Type'] = "application/x-www-form-urlencoded"
    } else if (contentType == 'form-multipart') {
        config.headers['Content-Type'] = "multipart/form-data"
    }

    return config
}, error => {
    console.error(error)
    Promise.reject(error);
})


// 响应拦截
service.interceptors.response.use(response => {
    // 服务器响应的数据中的状态码
    const errCode = response.data.errorCode
    const flag = response.data.flag;
    if (errCode === 0 || flag) {
        return response.data.data;
    }
    //console.log("data.data1");
    const msg = response.data.error
    if (errCode === 40002 || errCode === 40001|| !flag) {
        ElMessage.warning(msg)
        router.replace('/login')
        return ;
    } else if (msg) {
        ElMessage.error(msg)
    } else {
        ElMessage.warning(response.data.msg || '啊哦，发生了未知错误')
    }
    // todo 未知错误，直接跳到错误页面
    router.replace('/not_find')
    return ;
    //return Promise.reject('error')
}, error => {
    console.log("error:")
    console.log(error)
    // const { status } = error.response
    // if (status === 401) {
    //     ElMessage.warning('前辈需要登录后才能继续当前操作哦')
    // } else if (status === 403) {
    //     ElMessage.warning('前辈权限不足，无法执行当前操作')
    // } else if (status === 404) {
    //     ElMessage.warning('请求的资源不存在哦')
    // } else if (status >= 500) {
    //     ElMessage.warning('服务器出现异常啦')
    // }

    return Promise.reject(error);
})


export default service
